namespace :js_named_routes do
  desc 'Generate static js named routes file.'
  task :freeze => :environment do
    result = <<-EOS
function is_object_empty(obj){
  var result = true;
  for(var key in obj){
  if(typeof(obj[key]) == 'function')
    continue;
  result = false;
  break;
  }
  return result;
}

function join_object_to_query_string(obj){
  var arr = [];
  for(var key in obj){
  if(typeof(obj[key]) == 'function')
    continue;
  var value = obj[key];
        var entry = key + "=" + encodeURIComponent(value);
        arr.push(entry);
  }
  var result = arr.join('&');
  return result;
}

function translate_path(path_template,args){
  if(args.length == 0){
    return path_template;
  }
  var params = {};
  if(args.length ==1){
    if(typeof(args[0]) == 'number' || typeof(args[0]) == 'string'){
      var id = args[0];
      params['id'] = id;
    }else{
      params = args[0];
    }
  }else if(args.length == 2){
    if(typeof(args[1]) == 'number' || typeof(args[1]) == 'string'){
      params[ args[0] ] = args[1];
    }else{
        params = args[1];
        params['id'] = args[0];
    }
  }else{
    for(var i=0;i < args.length;i+=2){
        var key = args[i];
        var value = args[i+1];
        params[key] = value;
    }
  }
  var m = path_template.match(/\\:\\w+/g);
  if(m == null){
      m = {};
      m.length = 0;
  }
  var result = path_template;
  for(var i=0;i<m.length;i++){
    var key =  m[i].substring(1);
    result = result.replace(m[i], params[key]);
    delete params[key]
  }
  if(!is_object_empty(params)){
    var query_string = join_object_to_query_string(params);
    if(result.indexOf('?') == -1){
        result += '?';
    }
    result += query_string;
   }
  return result;
}
    EOS
    ActionController::Routing::Routes.named_routes.each do |k, v|
      if not /^formatted/ === k.to_s
        result += <<-EOS

function #{k.to_s}_path(){
  var path_template = '#{v.to_s.split[1]}';
  return translate_path(path_template,arguments);
}
        EOS
      end
    end
    
    File.open(RAILS_ROOT + '/vendor/plugins/js_named_routes/public/javascripts/js_named_routes.js', 'w') do |file|
      file.puts result
    end
  end
end